package com.example.rental.controller;
import com.example.rental.entity.Oder;
import com.example.rental.entity.dto.OderDto;
import com.example.rental.result.Result;
import com.example.rental.service.HouseService;
import com.example.rental.service.OderService;
import com.example.rental.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/order")
@Api(tags = "订单到期操作操作接口文档",description = "订单提取，订单删除")
public class OderController {

    @Autowired
    private OderService oderService;
    @Autowired
    private UserService userService;
    @Autowired
    private HouseService houseService;
    @GetMapping("/del")
    public Result<Integer> deleteOderByOderid(Integer orderid){
        return Result.ok(oderService.deleteOderByOderid(orderid));
    }
    @PostMapping("/add")
    public Result addOdre(@RequestBody OderDto oderDto){
        List<Integer> statusList=userService.searchUserByUsername(oderDto.getOrderUser());
        if(statusList.size()==0){
            return Result.error(200,"不存在用户");
        }
        for (Integer integer : statusList) {
            if(integer == 0|| integer==null){//不存在用户或者账号冻结
                return Result.error(200,"账号冻结");
            }
        }
        List<Integer> statusList2=houseService.searchHouseByHouseid(oderDto.getHouseid());
        if(statusList2.size()==0){
            return Result.error(200,"不存在房屋");
        }
        for (Integer integer : statusList2) {
            if(integer == 1){//不存在房屋或者房屋正在使用中！
                return Result.error(200,"房屋正在使用中");
            }
        }
        oderService.addOder(oderDto);
        if(oderDto.getOrderAdmin() != "" ) {
            houseService.updateHouseByHouseid(oderDto.getHouseid());
        }
        return Result.ok(oderDto);
    }
    @PostMapping("/search")
    public Result getOders(@RequestBody OderDto oderDto){
        Result list = oderService.getOders(oderDto);
        return list;
    }
    @PostMapping("/update")
    public Result updateOder(@RequestBody Oder oder){
        oderService.updateOder(oder);
        if(oder.getOrderAdmin() != "" && oder.getStatus() == 1) {
            houseService.updateHouseByHouseid(oder.getHouseid());
        }else if(oder.getOrderAdmin() != "" && oder.getStatus() == 0){
            houseService.updateAllHouse(oder);
        }
        return Result.ok(oder);
    }
    @PostMapping("/updateAll")
        public Result updateAllOder (@RequestBody List<Oder> orderList){
        System.out.println(orderList.toString());
        orderList.stream().forEach(item->{
            houseService.updateAllHouse(item);
            oderService.updateAllOder(item);
        });
        return Result.ok();
    }
}
